package com.algorithm.dm.kmean;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.algorithm.dm.kmean.KMean.Centerable;
import com.algorithm.dm.kmean.KMean.Cluster;
import com.algorithm.dm.kmean.KMean.Distanceable;

public class TestKMean {

	@Test
	public void testInsert() throws Exception {
		List<Integer> nums = new ArrayList<Integer>();
		for (int i = 0; i < 50; i++) {
			nums.add((i * i) + (int)(Math.random() * 1000));
		}
		Distanceable dis = new Distanceable() {
			@Override
			public double distance(Object obj1, Object obj2) {
				return Math.abs((Integer) obj1 - (Integer) obj2);
			}
		};
		Centerable cen = new Centerable() {
			public Object center(List<Object> objs) {
				int sum = 0;
				for (int i = 0; i < objs.size(); i++) {
					sum += (Integer) objs.get(i);
				}
				double avg = 0;
				if (sum > 0) {
					avg = sum / objs.size();
				}
				int index = 0;
				double min = Double.MAX_VALUE;
				for (int i = 0; i < objs.size(); i++) {
					if (Math.abs((Integer) objs.get(i) - avg) < min) {
						min = Math.abs((Integer) objs.get(i) - avg);
						index = i;
					}
				}
				return objs.get(index);
			}
		};
		KMean<Integer> km = new KMean<Integer>(10, 1000, dis, cen, nums);
		km.cluster();
		Cluster[] results = km.result();
		for (Cluster cluster : results) {
			System.out.println(cluster);
		}
	}
}
